package com.ct.application.shipping.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ct.application.commons.vo.StatusRequest;
import com.ct.application.shipping.model.po.ChuanBoXinXiSavePO;
import com.ct.application.shipping.model.po.ChuanBoXinXiSearchPO;
import com.ct.application.shipping.model.po.ChuanBoZhiWeiSavePO;
import com.ct.application.shipping.model.po.SysParameterSearchPO;
import com.ct.application.shipping.model.vo.ChuanBoXinXiVO;
import com.ct.application.shipping.model.vo.SysParameterVO;
import com.ct.application.shipping.service.ChuanBoXinXiService;
import com.ct.application.sysuser.model.vo.SysUserDetailVO;
import com.ct.application.sysuser.service.ISystemUserService;
import com.ct.repository.commons.BaseServiceImpl;
import com.ct.shipping.mapper.ChuanBoXinXiMapper;
import com.ct.shipping.orm.ChuanBoXinXiDO;
import com.ct.shipping.orm.ChuanBoZhiWeiDO;
import com.ct.shipping.orm.ChuanYuanKuDO;
import com.ct.shipping.orm.SysParameterDO;
import com.ct.utils.result.StatusEnums;
import com.ct.utils.threadlocal.UserThreadLocal;
import com.ct.utils.valid.ValidatorUtil;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 船舶信息 服务实现类
 * </p>
 *
 * @author carlo
 */
@Service
public class ChuanBoXinXiServiceImpl extends BaseServiceImpl<ChuanBoXinXiMapper, ChuanBoXinXiDO>
            implements ChuanBoXinXiService {

    @Resource
    private ISystemUserService systemUserService;


    @Override
    public List<ChuanBoXinXiVO> findChuanBoXinXisList(){
        LambdaQueryWrapper<ChuanBoXinXiDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ChuanBoXinXiDO::getZhuangTai, StatusEnums.STATUS.getCode());
        lambdaQueryWrapper.orderByDesc(ChuanBoXinXiDO::getCreateTime);
        return tranferListBo(this.list(lambdaQueryWrapper),ChuanBoXinXiVO.class);
    }

    /**
     * 查询分页列表数据
     * 关键字搜索: 中文名、IMO、船舶识别号
     */
    public Page<ChuanBoXinXiVO> findChuanBoXinXi(ChuanBoXinXiSearchPO searchPO){
        LambdaQueryWrapper<ChuanBoXinXiDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //标志 1:船舶信息模块调用 2:船员调配模块调用
        Integer flag = searchPO.getFlag();
        if (flag != null && flag == 2) {
            // 查询用户分组
            SysUserDetailVO sysUserDetailVO = systemUserService.selectById(UserThreadLocal.get().getId());
            String chuanboIds = sysUserDetailVO.getChuanboIds();
            if (StringUtils.isNotEmpty(chuanboIds)) {
                List<Long> collect = Arrays.stream(chuanboIds.split(",")).toList().stream().map(Long::parseLong).collect(Collectors.toList());
                lambdaQueryWrapper.in(ChuanBoXinXiDO::getId,collect);
            } else{
                return null;
            }
        }

        if(StringUtils.isNotEmpty(searchPO.getKeyword())){
            lambdaQueryWrapper.and(w->{
                w.like(ChuanBoXinXiDO::getZhongWenMing,searchPO.getKeyword())
                .or()
                .like(ChuanBoXinXiDO::getImo,searchPO.getKeyword())
                .or()
                .like(ChuanBoXinXiDO::getShiBieHao,searchPO.getKeyword());
            });
        }
        lambdaQueryWrapper.orderByDesc(ChuanBoXinXiDO::getCreateTime);

        Page<ChuanBoXinXiDO> page = new Page<>(searchPO.getPageNo(),searchPO.getPageSize());
        Page<ChuanBoXinXiDO> page1 = this.page(page, lambdaQueryWrapper);
        return tranferPageBo(page1, ChuanBoXinXiVO.class);
    }



    /**
     * 新增船舶
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean saveChuanBoXinXi(ChuanBoXinXiSavePO savePO){
        savePO.setId(null); //新增不需要id
        if (StringUtils.isEmpty(savePO.getZhongWenMing() )) {
            throw new RuntimeException("船舶名称不能为空");
        }
        if (StringUtils.isEmpty(savePO.getLeiXing())) {
            throw new RuntimeException("船舶类型不能为空");
        }
        ChuanBoXinXiDO queryChuanBoXinXi = this.lambdaQuery()
                .eq(ChuanBoXinXiDO::getZhongWenMing, savePO.getZhongWenMing())
                .one();
        if (queryChuanBoXinXi != null) {
            throw new RuntimeException("《"+savePO.getZhongWenMing()+"》船名已存在，请更换");
        }

        ChuanBoXinXiDO chuanBoXinXiDO = tranferBo(savePO, ChuanBoXinXiDO.class);
        if (Objects.nonNull(chuanBoXinXiDO)){
            chuanBoXinXiDO.setSystemId(UserThreadLocal.get().getSystemId());
            chuanBoXinXiDO.setSystemName(UserThreadLocal.get().getSystemName());
            return this.save(chuanBoXinXiDO);
        }
        return false;
    }

    /**
     * 修改
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateChuanBoXinXi(ChuanBoXinXiSavePO savePO){
        if (savePO.getId() == null) {
            throw new RuntimeException("id不能为空");
        }
        if (StringUtils.isEmpty(savePO.getZhongWenMing())) {
            throw new RuntimeException("船舶名称不能为空");
        }
        if (StringUtils.isEmpty(savePO.getLeiXing())) {
            throw new RuntimeException("船舶类型不能为空");
        }
        ChuanBoXinXiDO queryChuanBoXinXi = this.lambdaQuery()
                .eq(ChuanBoXinXiDO::getZhongWenMing, savePO.getZhongWenMing())
                .ne(ChuanBoXinXiDO::getId, savePO.getId())
                .one();
        if (queryChuanBoXinXi != null) {
            throw new RuntimeException("《"+savePO.getZhongWenMing()+"》船名已存在，请更换");
        }
        if(!savePO.getShangChuanChuQin().matches("^(-?\\d+(\\.\\d+)?)$")){
            throw new RuntimeException("上船工作时间只能是数字");
        }
        if(!savePO.getXiaChuanChuQin().matches("^(-?\\d+(\\.\\d+)?)$")){
            throw new RuntimeException("下船当天出勤只能是数字");
        }

        ChuanBoXinXiDO chuanBoXinXiDO = tranferBo(savePO, ChuanBoXinXiDO.class);
        if (Objects.nonNull(chuanBoXinXiDO)){
            return this.updateById(chuanBoXinXiDO);
        }
        return false;
    }


    /**
     * 删除船舶
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean del(Long id){
        return this.removeById(id);
    }


    /**
     * 状态修改。
     * 0:停用、1:启用
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateStatus(StatusRequest statusRequest){
        if(ValidatorUtil.isNumeric(statusRequest.getValue())) {
            return this.updateStatus(statusRequest.getId(), statusRequest.getField(), Integer.parseInt(statusRequest.getValue()));
        }else{
            return this.updateStatusStr(statusRequest.getId(), statusRequest.getField(), statusRequest.getValue());
        }
    }


    @Override
    public ChuanBoXinXiVO getChuanBoXinXi(Long id){
        ChuanBoXinXiDO byId = getById(id);
        return tranferBo(byId,ChuanBoXinXiVO.class);
    }

}
